<?php
declare (strict_types = 1);

namespace app\model;

use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\model\contract\Modelable;

/**
 * @mixin Model
 */
class ProductCategories extends Model
{
    // 获取所有分类
    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getAllCategories(): Collection|array
    {
        return $this->select();
    }

    /**
     * 批量创建分类
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function createCategory($data): array
    {
        //检测是否和其他的名称重复
        $nameStr = implode(',',array_column($data,'name'));
        if ($this->whereIn('name', $nameStr)->find()) {
            return modelResponse(403, '分类名称重复');
        }
        try {
            $this->saveAll($data);
            return modelResponse(200,'分类添加成功');
        }catch (\Exception $e){
            return modelResponse(400, $e->getMessage());
        }
    }

    // 更新分类
    public function updateCategory($id, $data): array
    {
        //检测是否和其他的名称重复
        if ($this->where('name', $data['name'])->where('id', '<>', $id)->find()) {
            return modelResponse(403, '分类名称重复');
        }
        try {
            $this->where('id', $id)->update($data);
            return modelResponse(200,'分类更新成功');
        }catch (\Exception $e){
            return modelResponse($e->getCode(), $e->getMessage());
        }
    }

    // 删除分类

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function deleteCategory($id): array
    {
        //检测产品分类是否存在产品，如果有则不允许删除
        $product = (new Product)->where('category_id', $id)->find();
        if ($product) {
            return modelResponse(400, '该分类下存在产品，不允许删除');
        }
        try {
            $this->where('id', $id)->delete();
            return modelResponse(200, '分类删除成功');
        }catch (\Exception $e){
            return modelResponse(400, $e->getMessage());
        }

    }
}